﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.RoleMenuCommand;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.RoleMenuCommandHandler
{
    /// <summary>
    /// 反填获取菜单命令执行
    /// </summary>
    public class GetFanTianCommandHandler : IRequestHandler<GetFanTianCommand, APIResult<List<MenuDTOs>>>
    {
        private readonly IBaseRepository<RoleMenuModel> roleMenuRepos;
        private readonly IBaseRepository<MenuModel> menuRepos;

        public GetFanTianCommandHandler(IBaseRepository<RoleMenuModel> roleMenuRepos,IBaseRepository<MenuModel> menuRepos)
        {
            this.roleMenuRepos = roleMenuRepos;
            this.menuRepos = menuRepos;
        }

        /// <summary>
        /// 反填获取菜单(名称,id)
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<List<MenuDTOs>>> Handle(GetFanTianCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<MenuDTOs>> result = new APIResult<List<MenuDTOs>>();

            //var list = roleMenuRepos.GetAll().Result.Where(x => x.RoleId == request.RoleId);
            //result.Code = APIEnum.查询成功;
            //result.Msg = APIEnum.查询成功.ToString();
            //result.data =list.ToList();
            //return await Task.FromResult(result);
             
            var list = from a in roleMenuRepos.GetAll().Result
                       join b in menuRepos.GetAll().Result on a.MenuId equals b.MenuId
                       where a.RoleId == request.RoleId || request.RoleId == null
                       select new MenuDTOs
                       {
                           MenuId = a.MenuId,
                           RoleMenuId = a.RoleMenuId,
                           RoleId = a.RoleId,
                           MenuName = b.MenuName,
                           Url = b.Url, 
                           ParentId = b.ParentId,
                       };
            int count = list.Count();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功 + $"共{count}条";
            result.data = list.ToList();
            return await Task.FromResult(result);
        }
    }
}
